from django.shortcuts import render,redirect
from django.urls import reverse # 导入反向解析模块
from django.views import View
from django import http
from django.contrib.auth import login,authenticate,logout # 导入实现状态保持的函数
# 导入数据库错误异常
from django.db import DatabaseError
from django_redis import get_redis_connection

from users.models import User,Address
# 前面有报错，所以没有提示
from meiduo_mall.utils.response_code import RETCODE
from django.contrib.auth.mixins import LoginRequiredMixin # 导入模块
import re,json,logging
from celery_tasks.email.tasks import send_verify_email # 导入发送邮件的函数
from users.utils import generate_verify_email_url # 产生验证邮件链接
# 创建日志输出器
logger=logging.getLogger("django")
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from users.utils import check_verify_email_token
from . import constants

from goods.models import SKU
from carts.utils import merge_carts_cookies_redis # 导入合并购物车工具类

class UserBrowseHistory(LoginRequiredJSONMixin, View):
    """用户浏览记录"""
    def post(self, request):
        """保存用户浏览记录"""
        # 1. 接收参数
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        sku_id = json_dict.get("sku_id")
        # 2.校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden("参数sku_id错误")
        # 3. 执行业务逻辑： 保存sku_id到redis数据库中
        redis_conn = get_redis_connection("history")
        user = request.user
        pipeline = redis_conn.pipeline()
        # 先去重
        pipeline.lrem("history_%s"%user.id,0,sku_id)
        # 再保存：最近浏览的历史记录在最前面
        pipeline.lpush("history_%s"%user.id,sku_id)
        # 最后截取
        pipeline.ltrim("history_%s"%user.id,0,4)
        #执行指令
        pipeline.execute()

        # 4. 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK"})

    def get(self,request):
        """
        查询用户商品历史浏览记录
        :param request:
        :return:
        """
        user = request.user
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%user.id,0,-1) # 0,4

        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                "id":sku.id,
                "name":sku.name,
                "price":sku.price,
                "default_image_url":sku.default_image.url
            })

        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","skus":skus},json_dumps_params={"ensure_ascii":False})
class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """设置地址标题"""
    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            # 查询地址
            address = Address.objects.get(id=address_id)
            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})
        # 4.响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})

class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""
    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)
            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})
        # 响应设置默认地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})
class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""
    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self,request,address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})
        # 响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})

class AddressCreateView(LoginRequiredJSONMixin,View):
    """新增地址"""
    def post(self,request):
        """实现新增地址逻辑"""

        # 判断用户地址数量是否超过上限
        # count = Address.objects.filter(user=request.user).count()
        # 查询当前登录用户地址的数量
        count = request.user.addresses.count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return http.JsonResponse({"code": RETCODE.THROTTLINGERR,
                                      "errmsg": "超出用户地址上限"})

        # 接收参数
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 保存用户传入的地址信息
        try:
            address=Address.objects.create(
                user=request.user,
                title=receiver, #标题默认就是收货人
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            # 如果登录用户，没有默认地址，我们需要指定默认地址
            if not request.user.default_address:
                request.user.default_address=address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code":RETCODE.DBERR,"errmsg":"新增地址失败"})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应新增地址结果：需要将新增的地址返回给前端渲染
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"新增地址成功",
                                  "address":address_dict})

class AddressView(LoginRequiredMixin,View):
    """用户收货地址"""
    def get(self,request):
        """查询并展示用户地址信息"""
        # 获取当前登录的用户对象
        login_user = request.user
        # 使用当前登录的用户和is_deleted=False作为条件查询地址数据
        addresses = Address.objects.filter(user=login_user, is_deleted=False)
        address_list = []
        # 将用户地址模型列表转化成字典列表：因为JsonResponse和Vue.js不认识模型类
        # 只有django和jinja2模板引擎认识
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_list.append(address_dict)
        # 构造上下文对象
        context = {
            # 当用户删除所有数据后，没有默认收货地址，获取值为None
            # 'default_address_id': login_user.default_address_id or '0',
            'default_address_id': login_user.default_address_id,
            'addresses': address_list,
        }
        return render(request, 'user_center_site.html', context)

class VerifyEmailView(View):
    """验证邮箱"""
    def get(self,request):
        # 接收参数
        token = request.GET.get("token")
        # 校验参数
        if not token:
            return http.HttpResponseForbidden("缺少参数token")
        # 从token中提取用户信息 user_id===>user
        user = check_verify_email_token(token)
        if not user:
            return http.HttpResponseBadRequest("无效的token")
        # 将用户的email_active字段设置为True
        try:
            user.email_active=True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError("激活邮箱失败")
        # 响应结果：重定向到用户中心
        return redirect(reverse("users:info"))
# LoginRequiredMixin继承这个类不可以，因为这个类内部返回的是
# HttpResponseRedirect，而当前函数返回的是JsonResponse
class EmailView(LoginRequiredJSONMixin,View):
    """添加邮箱"""
    def put(self,request):
        # 1. 接收参数
        # request.body是bytes类型的数据，通过decode()解码成字符串
        json_str = request.body.decode() # 获取请求体中的参数
        json_dict = json.loads(json_str)
        email = json_dict.get("email")
        # 2. 校验参数
        if not email:
            return http.HttpResponseForbidden('缺少email参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        try:
            # 执行业务逻辑：将用户传入的邮箱保存到用户数据库的email字段中
            request.user.email=email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code":RETCODE.DBERR,"errmsg":"添加邮箱失败"})

        # 发送邮箱验证邮件
        verify_url = generate_verify_email_url(request.user)
        # send_verify_email(email,verify_url) # 错误的写法
        send_verify_email.delay(email,verify_url) # 一定要记得调用delay()函数

        # 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK"})
class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        """提供用户中心页面"""
        # 如果LoginRequiredMixin类判断出用户已经登录，那么request.user就是当前登录的用户对象
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, "user_center_info.html",context)
class LogoutView(View):
    """用户退出登录"""
    def get(self,request):
        """实现用户退出登录的逻辑"""
        # 清除状态保持信息
        logout(request)
        # 退出登录后重定向到首页
        response = redirect(reverse("contents:index"))
        # 删除cookie中的用户名
        response.delete_cookie("username")
        # 响应结果
        return response


class LoginView(View):
    """用户登录"""
    def get(self,request):
        """提供登录界面"""
        from django.middleware.csrf import rotate_token, get_token
        rotate_token(request)  # 生成csrftoken随机字符串
        csrftoken = get_token(request)  # 取出csrftoken随机字符串
        response = render(request,"login.html")
        response.set_cookie("csrftoken", csrftoken, max_age=15 * 24 * 3600)

        return response
    def post(self,request):
        """实现登录逻辑"""
        # 接收参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        remembered = request.POST.get("remembered")
        # 校验参数
        if not all([username,password]):
            return http.HttpResponseForbidden("缺少必传参数")
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$",username):
            return http.HttpResponseForbidden("请输入正确的用户名或者手机号")
        if not re.match(r"[a-zA-Z0-9]{8,20}",password):
            return http.HttpResponseForbidden("密码最少8位，最长20位")
        # 认证用户：使用账号查询用户是否存在，如果存在再校验密码是否正确
        user = authenticate(username=username,password=password)
        if user is None:
            # 显示错误提示信息
            return render(request,'login.html',{"account_errmsg":"账号或者密码错误"})
        # 状态保持
        login(request,user)
        # 使用remembered确定状态保持周期，实现记住登录状态
        if remembered!="on":
            # 没有记住登录状态：状态保持在浏览器会话结束就销毁
            request.session.set_expiry(0) # 单位是秒
        else:
            # 记住登录状态：状态保持周期为2周，默认是两周
            request.session.set_expiry(None)

        # 响应结果：重定向到首页
        next = request.GET.get("next")
        if next:
            # 重定向到next指定的页面
            response=redirect(next)
        else:
            # 重定向到首页
            response = redirect(reverse("contents:index"))
        # response.set_cookie("key","value","expire")
        response.set_cookie("username",user.username,max_age=3600*24*15)
        # 用户登录成功，合并cookie购物车中的数据到redis购物车
        response=merge_carts_cookies_redis(request=request,user=user,response=response)
        return response
class UsernameCountView(View):
    """判断用户名是否重复"""
    def get(self,request,username):
        """
        :param username:用户名
        :return: 返回JSON字符串
        """
        # 接收参数和校验参数，在路由配置中已经做了，不需要重复做了
        # 实现主体业务逻辑：使用username查询对应的记录数(filter返回满足条件的结果集)
        count = User.objects.filter(username=username).count()
        # 响应结果
        # return http.JsonResponse({"code":0,"errmsg":"OK","count":count})
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})
class MobileCountView(View):
    def get(self,request,mobile):
        """
        判断手机号是否重复
        :param request:
        :param mobile: 手机号
        :return:
        """
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "count": count})
# Create your views here.
class RegisterView(View):
    """用户注册视图"""
    def get(self,request):
        """提供展示用户注册页面的效果"""
        return render(request,"register.html")

    def post(self,request):
        """实现用户注册业务逻辑"""
        # 1. 接收参数
        POST = request.POST # 接收请求体中传递过来的数据，是一个QueryDict类型的对象
        print("POST=",POST,",type=",type(POST))
        username = POST.get("username")
        password = POST.get("password")
        password2 = POST.get("password2")
        mobile = POST.get("mobile")
        sms_code_client = POST.get("sms_code")
        allow = POST.get("allow")
        print("username=",username,",password=",password,",password2=",password2,
              ",mobile="+mobile+",allow="+allow)
        # 2. 校验参数，前后端的校验逻辑需要分开，避免恶意用户越过前端逻辑发请求，
        # 要保证后端的安全，前后端校验逻辑相同
        # 判断参数是否齐全：all([列表])：校验列表中元素是否为空，只要有一个为空，则返回False
        if not all([username,password,password2,mobile,allow]):
            # return "如果缺少必传参数，响应错误提示信息，403"
            return http.HttpResponseForbidden("缺少必传参数")
        # 判断用户名是否是5-20个字符
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$",username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 判断短信验证码是否正确
        redis_conn = get_redis_connection("verify_code")
        sms_code_server = redis_conn.get("sms_%s"%mobile)
        if sms_code_server is None:
            return render(request,"register.html",{"sms_code_errmsg":"短信验证码已失效"})
        if sms_code_client!=sms_code_server.decode():
            return render(request,"register.html",{"sms_code_errmsg":"输入短信验证码错误"})
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 为了方便测试，可以这样写
        # return render(request, "register.html", {"register_err_msg": "注册失败"})

        try:
            # 3. 执行业务逻辑：保存注册数据，是注册业务的核心
            # 如果用户以后还需要这个用户对象就使用变量接收一下，现在不确定，暂时不接收
            user = User.objects.create_user(username,password=password,mobile=mobile)
        except DatabaseError:
            return render(request,"register.html",{"register_err_msg":"注册失败"})

        # 实现状态保持
        login(request,user)

        # 4. 响应结果：重定向到首页
        # 响应结果：重定向到首页
        response = redirect(reverse("contents:index"))
        # response.set_cookie("key","value","expire")
        response.set_cookie("username", user.username, max_age=3600 * 24 * 15)
        return response


